package com.ihrm.system.controller;


import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.PageResult;
import com.ihrm.common.entity.Result;
import com.ihrm.common.exception.CommonException;
import com.ihrm.common.utils.QiniuUploadUtil;
import com.ihrm.domain.system.LoginDto;
import com.ihrm.domain.system.ProfileResult;
import com.ihrm.domain.system.User;
import com.ihrm.system.client.DepartmentFeignClient;
import com.ihrm.system.service.UserService;
import com.ihrm.system.utils.BaiduAiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentFeignClient departmentFeignClient;

    @Autowired
    private BaiduAiUtil baiduAiUtil;

    //测试通过系统微服务调用企业微服务方法
    @GetMapping("/test/{id}")
    public Result findDeptById(@PathVariable String id) {
        Result res = departmentFeignClient.findById(id);
        return Result.SUCCESS(res.getData());
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto) {
        String token = userService.login(loginDto);
        return Result.SUCCESS(token);
    }

    /**
     * 获取用户详情包括权限
     */
    @PostMapping("/profile")
    public Result profile(HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        ProfileResult profile = userService.getUserProfileByUserId(userId);
        return Result.SUCCESS(profile);
    }

    //    新增员工
    @PostMapping("/user")
    public Result addUser(@RequestBody User user) {
        user.setCompanyId(parseCompanyId());
        user.setCompanyName(parseCompanyName());
        Integer num = userService.insert(user);
        if (num > 0) {
            return Result.SUCCESS();
        } else {
            return Result.FAIL();
        }
    }

    //根据id查询员工信息
    @GetMapping("/user/{id}")
    public Result updateUser(@PathVariable String id) {
        User user = userService.selectById(id);
        if (user == null) {
            throw new CommonException(10000, "用户不存在");
        }
        return Result.SUCCESS(user);
    }

    //分页查询员工
    @GetMapping("/user")
    public Result pageFind(Integer page, Integer size, @RequestParam Map<String, Object> map) {
        map.put("companyId", parseCompanyId());
        PageResult pageResult = userService.pageFind(page, size, map);
        return Result.SUCCESS(pageResult);
    }

    //更新员工信息
    @PutMapping("/user/{id}")
    public Result updateUser(@PathVariable String id, @RequestBody User user) {
        Integer num = userService.update(user);
        if (num > 0) {
            return Result.SUCCESS();
        } else {
            return Result.FAIL();
        }
    }

    //删除员工
    @DeleteMapping("/user/{id}")
    public Result delUserById(@PathVariable String id) {
        Integer num = userService.del(id);
        if (num > 0) {
            return Result.SUCCESS();
        } else {
            return Result.FAIL();
        }
    }

    /**
     * 分配角色
     */
    @PutMapping("/user/assignRoles")
    public Result assignRoles(@RequestBody Map<String, Object> map) {
        //1.获取被分配的用户id
        String userId = (String) map.get("id");
        //2.获取到角色的id列表
        List<String> roleIds = (List<String>) map.get("roleIds");
        //3.调用service完成角色分配
        userService.assignRoles(userId, roleIds);
        return Result.SUCCESS();
    }

    /**
     *上传头像
     */
    @PostMapping("/user/upload/{id}")
    public Result uploadImage(@PathVariable String id, MultipartFile file) throws Exception {
        User user = userService.selectById(id);
        String url = new QiniuUploadUtil().upload(user.getId(), file.getBytes());
        if (url != null) {
            String image = Base64Utils.encodeToString(file.getBytes());
            Boolean boo = baiduAiUtil.faceCheck(image);
            if(!boo) {
                throw new CommonException(10002, "请上传人面相");
            }
            //人脸注册，本应该放在关系信息的哪里
            Boolean aBoolean = baiduAiUtil.faceRegister(user.getId(), image);
            if(!aBoolean) {
                throw new CommonException(10002, "人脸注册失败");
            }
            user.setStaffPhoto(url);
            userService.update(user);
        }
        return Result.SUCCESS(url);
    }
}
